package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * sky-take-out
 * com.sky.service.user.impl
 * C端用户相关接口实现类
 * @author Ablecisi
 * @version 1.0
 * 2025/4/4
 * 10:24
 */
@Service
public class UserServiceImpl implements UserService {
    // 微信登录接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(WeChatProperties weChatProperties, UserMapper userMapper) {
        this.weChatProperties = weChatProperties;
        this.userMapper = userMapper;
    }

    /**
     * 微信登录
     * @param userLoginDTO 用户登录信息
     * @return User
     */
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        // 1.调用微信接口服务获得当前用户的openid
        String openid = getOpenID(userLoginDTO.getCode());

        // 2.判断openid是否为空，如果为空，抛出异常
        if (openid == null) {
            // 2.1 如果openid为空，抛出异常
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 3.判断当前的微信用户是否是一个新用户，如果是新用户，保存到数据库中
        User user = userMapper.getUserByOpenId(openid);

        // 4.如果是新用户，自动完成注册，
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 5.返回用户信息
        return user;
    }

    /**
     * 调用微信接口服务获得当前用户的openid
     * @param code 微信登录凭证
     * @return openid
     */
    private String getOpenID(String code) {
        // 1.1 拼接请求参数
        Map<String, String> claims = new HashMap<>();
        claims.put("appid", weChatProperties.getAppid());
        claims.put("secret", weChatProperties.getSecret());
        claims.put("js_code", code);
        claims.put("grant_type", "authorization_code");
        String responseJson = HttpClientUtil.doGet(WX_LOGIN, claims);
        JSONObject jsonObject = JSON.parseObject(responseJson);
        // 1.2 获取openid
        return jsonObject.getString("openid");
    }
}
